<?php
	if(getRequestParameter("search") !== false)
	{
		$messages = array();
		
		$searchTerm = getRequestParameter("search");
		if(strlen($searchTerm) >= 3)
		{
			$products = searchProducts($searchTerm);
			
			$productCount = $products[0]["num_rows"];
			if($productCount == 0)
			{
				$messages["result_text"] = translate("search_no_results");
			}
			else
			{
				if($productCount == 1)
				{
					$messages["result_text"] = $productCount ." ". translate("single_search_result").".";
				}
				else
				{
					$messages["result_text"] = $productCount ." ". translate("search_results").".";
				}
				
				
				$content = "<table class='table'><tbody>";
				
				foreach($products as $product)
				{
					$content .= "<tr>";
					$content .= '<td><img alt="" style="height:30px;" src="'.scripts_url().$product["images"][0]["thumb_name"].'"/></td>';
					$content.= "<td><a href='{$product["url"]}'>{$product["name"]}</a>";
					$content .= "</tr>";
				}
				if($products[0]["num_rows"] > 5)
				{
					$searchPage = get_site_page_by_slug("search", $_SESSION["language"]["id"]);
					$content .= "<tr><td colspan='2' class='text-center bold'><a href='".site_url().$searchPage["url"].".html?search_term={$searchTerm}'>".translate("see_all_results")."</a></tr>";
				}
				$content .= "</table>";
				
				$messages["results"] = $content;
			}
		}
		else
		{
			$messages["result_text"] = translate("search_minimum_characters");
		}
		
		echo json_encode($messages);
	}
	
	if(getRequestParameter("get_compare_list") !== false)
	{
		if(isset($_SESSION["compare"]) && count($_SESSION["compare"]) > 1)
		{
			$productCount = count($_SESSION["compare"]);
			$index = 1;
			?>
			<div class="col-md-12">
				<div class="row">
					<table class="table table-hover">
						<thead>
							<tr>
								<th>#</th>
								<th><?php echo translate("product_name"); ?></th>
								<th><?php echo translate("category"); ?></th>
								<th><?php echo translate("properties"); ?></th>
								<th><?php echo translate("price"); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
								foreach($_SESSION["compare"] as $productID)
								{
									$product = getProductByField($productID, "id");
									if(isset($product["id"]))
									{
										echo "<tr>";
											echo "<td>{$index}</td>";
											echo "<td>{$product["name"]}</td>";
											echo "<td>";
											if(isset($product["parent_category"]["name"]))
											{
												echo $product["parent_category"]["name"];
											}
											
											if(isset($product["parent_category"]["name"]) && isset($product["category"]["name"]))
											{
												echo " / ";
											}
											
											if(isset($product["category"]["name"]))
											{
												echo $product["category"]["name"];
											}
											echo "</td><td>";
											foreach($product["properties"] as $key => $property)
											{
												echo $property["name"]."<br />";
												foreach($property["values"] as $value)
												{
													echo "<strong>" . $value["name"] . "</strong> ";
												}
												echo "<br />";
											}
											echo "</td>";
											echo "<td>{$product["price"]}</td>";
										echo "</tr>";
										$index++;
									}
								}
							?>
						</tbody>
					</table>
				</div>
			</div>
			
			<?php
			
		}
		else
		{
				
			echo '<div class="alert alert-danger">'.translate("compare_error_minimum").'</div>';
				
		}
	}
	
	if(getRequestParameter("add_to_compare") != false && getRequestParameter("add_to_compare")  > 0)
	{
		global $connection;
		
		$messages = array();
		
		$productID = getRequestParameter("add_to_compare");
		$product = getProductByField($productID, "id");
		
		if(isset($product["id"]))
		{
			if(isset($_SESSION["compare"][$productID]))
			{
				unset($_SESSION["compare"][$productID]);
				$action = "delete";
				$messages["success"] = translate("deleted_from_compare_list");
			}
			else
			{
				$_SESSION["compare"][$productID] = $productID;
				$action = "add";
				$messages["success"] = translate("added_to_compare_list");
			}
			
			$messages["action"] = $action;
		}
		else
		{
			$messages["error"] = translate("unknown_error");
		}
		
		$comparedProducts = 0;
		if(isset($_SESSION["compare"]))
		{
			$comparedProducts = count($_SESSION["compare"]);
		}
		
		$messages["compared_products"] = $comparedProducts;
		
		echo json_encode($messages);
		return false;
	}
	
	if(getRequestParameter("remake-products"))
	{
		
		$companyID = $parentCategoryID = $categoryID = false;
		
		$bestCategoryID = $companyID = false;
		
		if(getRequestParameter("company_id") && getRequestParameter("company_id") > 0)
		{
			$companyID = getRequestParameter("company_id");
		}
		
		if(getRequestParameter("parent_category_id") && getRequestParameter("parent_category_id") != "null")
		{
			$categoryID = $bestCategoryID = getRequestParameter("parent_category_id");
		}
		
		if(getRequestParameter("category_id") && getRequestParameter("category_id") != "null")
		{
			$parentCategoryID = $categoryID;
			$categoryID = $bestCategoryID = getRequestParameter("category_id");
		}
		
		if(getRequestParameter("sub_category_id") && getRequestParameter("sub_category_id") != "null")
		{
			$parentCategoryID = $categoryID;
			$categoryID = $bestCategoryID = getRequestParameter("sub_category_id");
		}
		
		$filters = null;
		if(getRequestParameter("filters") && getRequestParameter("filters") != "")
		{
			$filters = json_decode(getRequestParameter("filters"), true);
		}
		
		$sortOrder = "asc";
		if(getRequestParameter("sort_order") && getRequestParameter("sort_order") == "desc")
		{
			$sortOrder = "desc";
		}
		
		$sortBy = "id";
		if(getRequestParameter("sort_by") && getRequestParameter("sort_by") != "")
		{
			$sortBy = getRequestParameter("sort_by");
		}
		
		$type = 0;
		if(getRequestParameter("type") && getRequestParameter("type") != "")
		{
			$type = getRequestParameter("type");
		}
		
		$priceFilter = 0;
		if(getRequestParameter("price_filter") && getRequestParameter("price_filter") > 0)
		{
			$priceFilter = getRequestParameter("price_filter");
		}
		
		$itemsPerPage = 20;
		if(getRequestParameter("items_per_page") && getRequestParameter("items_per_page") > 0)
		{
			$itemsPerPage = getRequestParameter("items_per_page");
		}
		
		$products = filter_products($bestCategoryID, $type, $filters, $itemsPerPage, $sortBy, $sortOrder, $priceFilter, false);
		
		if(count($products) == 0 && $parentCategoryID)
		{
			//$products = filter_products(false, $type, $filters, $itemsPerPage, $sortBy, $sortOrder, $priceFilter, $parentCategoryID);
		}
		
		$totalItems = 0;
		if(isset($products[0]["num_rows"]))
		{
			$totalItems = $products[0]["num_rows"];
		}
		
		if(getRequestParameter("details") && getRequestParameter("details") == 1)
		{
			include("../../html-includes/common/product-detail-list.php");
		}
		else
		{
			include("../../html-includes/common/product-list.php"); 
		}
	}
	
	if(getRequestParameter("get_property_list") !== false)
	{
		if(getRequestParameter("product_id") !== false && getRequestParameter("product_id") > 0)
		{
			$productID = getRequestParameter("product_id");
			
			$product = getProductByField($productID, "id");
			if(isset($product["id"])):?>
				<h3><?php echo $product["name"]; ?></h3>
				<div class="col-md-7 col-xs-8">
					<div class="sellprop" id="productProperties">
						<h5><?php echo translate("product_properties"); ?>:</h5>
						<ul class="filterList holder" product_id="<?php echo $product["id"]; ?>">	
							<?php getPropertyList($product["properties"]); ?>
						</ul>
						<div class="clear"></div>
						<a href="#" title="" class="removeFilters hidden"><span class="glyphicon glyphicon-remove"></span> <?php echo translate("remove_filtes"); ?></a>
					</div>
				</div>
				<div class="col-md-5 col-xs-4 buttons">
					<div class="row priceDetails">
						<div class="productPrice"><?php echo $product["price"]; ?></div>
						<div class="stockInfo hidden"><!-- AJAX CONTENT --></div>
					</div>
					<div class="row">
						<div class="input-group pull-right">
							<input type="number" min="1" max="" class="form-control" name="quantity" placeholder="<?php echo translate("quantity"); ?>" />
							<div class="error hidden"></div>
					    </div>
					    <div class="clearfix"></div>
					</div>
				</div>
					
				<?php
				
			endif;
			
		}
		
		return false;
	}
	
	if(getRequestParameter("get_filter_list") !== false)
	{
		if(getRequestParameter("product_id") !== false && getRequestParameter("product_id") != "")
		{
			$productID = getRequestParameter("product_id");
			$product = getProductByField($productID, "id");
			if(isset($product["id"]))
			{
				$selectedValues = array();
				
				if(getRequestParameter("selected_values") && getRequestParameter("selected_values") != "")
				{
					$selectedValues = json_decode(getRequestParameter("selected_values"), true);
				}
				$possibleStocks = getPossibleStocks($product, $selectedValues);
				
				echo json_encode($possibleStocks);
				
				return false;
			}
			
		}
		
		$message["message"] = translate("unknown_error");
		echo json_encode($message);
		
		return false;
	}
	
	if(getRequestParameter("add_to_cart") !== false && getRequestParameter("product_id") !== false)
	{
		$productID = getRequestParameter("product_id");
		$product = getProductByField($productID, "id");
		
		$messages = array();
		
		if(isset($product["id"]))
		{
			$selectedValues = array();
				
			if(getRequestParameter("selected_values") && getRequestParameter("selected_values") != "")
			{
				$selectedValues = json_decode(getRequestParameter("selected_values"), true);
			}
			
			$possibleStocks = getPossibleStocks($product, $selectedValues);
			
			if(isset($possibleStocks["stock_id"]) && $possibleStocks["stock_id"] > 0)
			{
				$stockID = $possibleStocks["stock_id"];
				if(isset($possibleStocks["quantity"]) && $possibleStocks["quantity"] > 0)
				{
					if(getRequestParameter("quantity") !== false && is_numeric(getRequestParameter("quantity")) && getRequestParameter("quantity") > 0)
					{
						floor($quantity = getRequestParameter("quantity"));
						
						if(isset($_SESSION["cart"][$productID][$stockID]))
						{
							$quantity += $_SESSION["cart"][$productID][$stockID];
						}
						
						if($quantity <= $possibleStocks["quantity"])
						{
							
							$_SESSION["cart"][$productID][$stockID] = $quantity;
							$messages["success"] = translate("add_to_cart_success");
						}
						else
						{
							$messages["quantity"] = $messages["error"] = translate("add_to_cart_failed_no_stock");
						}
					}
					else
					{
						$messages["quantity"] = $messages["error"] = translate("add_to_cart_failed_no_quantity");
					}
				}
				else
				{
					$messages["quantity"] = $messages["error"] = translate("add_to_cart_failed_no_stock");
				}
			}
			else
			{
				$errorCount = 0;
				foreach($possibleStocks["property_values"] as $valueID => $propertyID)
				{
					$properties[$propertyID]["value"] = $valueID;
					if(!isset($properties[$propertyID]["value_count"]))
					{
						$properties[$propertyID]["value_count"] = 1;
					}
					else
					{
						$properties[$propertyID]["value_count"]++;
					}
					
					if($properties[$propertyID]["value_count"] == 2)
					{
						$errorCount++;
						$messages["property_errors"][$propertyID] = translate("select_property_value");
						$messages["error"] = translate("add_to_cart_error_select_properties");
					}
				}
				
				if($errorCount == 0)
				{
					
				}
			}
			
			echo json_encode($messages);
			
			return false;
		}
		else
		{
			$messages["error"] = translate("unkown_error");
		}
		
		$message["message"] = translate("unknown_error");
		echo json_encode($message);
		
		return false;
	}
	
	if(getRequestParameter("add_to_wishlist") !== false)
	{
		global $connection;
		
		$client = getLoginData();
		if(isset($client["id"]))
		{
			$productID = getRequestParameter("add_to_wishlist");
			$product = getProductByField($productID, "id");
			
			if(isset($product["id"]))
			{
				$checkWishList = $connection->fetch_one("SELECT * FROM users_wishlists WHERE product_id = ?", array($productID));
				if(isset($checkWishList["id"]))
				{
					$params["id"] = $checkWishList["id"];
					$connection->delete("users_wishlists", $params);
					
					$message["message"] = translate("wishlist_removed_product");
					$message["action"] = "delete";
				}
				else
				{
					$params["product_id"] = $productID;
					$params["user_id"] = $client["id"];
					$params["wish_price"] = $product["price"];
					$params["date"] = time();
					$connection->insert("users_wishlists", $params);
					
					$message["message"] = translate("wishlist_added_product");
					$message["action"]  = "add";
				}
				
			}
			else
			{
				$message["message"] = translate("wishlist_error_adding_product");
				$message["action"]  = "add";
			}
		}
		else
		{
			$loginPage = get_site_page_by_slug("login", $_SESSION["language"]["id"]);
			
			$message["message"] = translate("wishlist_need_to_login");
			$message["message"] .= "<a href='".site_url().$loginPage["url"].".html'>" . translate("log_in_now") . "</a>";
			$message["action"]  = "login";
		}
		
		echo json_encode($message);
		return false;
	}

	if(getRequestParameter("rate_product") !== false)
	{
		global $connection;
		
		if(getRequestParameter("product_id") !== false && getRequestParameter("product_id") != "" && getRequestParameter("rating") !== false)
		{
			$message = array();
			$productID = getRequestParameter("product_id");
			
			$product = getProductByField($productID, "id");
			
			if(isset($product["id"]))
			{
				$client = getLoginData();
				$ip = $_SERVER['REMOTE_ADDR'];
				
				$params[] = getRequestParameter("product_id");
				
				$query = "SELECT * FROM products_ratings WHERE product_id = ? ";
				if(isset($client["id"]))
				{
					$params[] = $client["id"];
					
					$query .= " AND client_id = ?";
				}
				else
				{
					$params[] = $ip;
					
					$query .= " AND ip = ?";
				}
				$checkVote = $connection->num_rows($query, $params);
				
				if($checkVote == 0)
				{
					if(isset($client["id"]))
					{
						$insertData["client_id"] = $client["id"];
					}
					$insertData["product_id"] = $product["id"];
					$insertData["rating"] = getRequestParameter("rating");
					$insertData["ip"] = $ip;
					
					$connection->insert("products_ratings", $insertData);
					
					$newRating = $connection->fetch_one("SELECT AVG(rating) AS new_rating FROM products_ratings WHERE product_id = ?", array($product["id"]));
					
					$message["rating"] = round($newRating["new_rating"]);
					$message["message"] = translate("product_rating_successful");
					
					echo json_encode($message);
				}
				else
				{
					$message["message"] = translate("product_rating_already_rated");
					echo json_encode($message);
				}
				return false;
			}
		}
		
		$message["message"] = translate("unknown_error");
				
		echo json_encode($message);
	}

		if(getRequestParameter("send_company_contact"))
		{
			$response = $errors = array();
			
			$product = $companyID = false;
			
			$client = getLoginData();
			
			$languageID = $_SESSION["language"]["id"];
			
			if(getRequestParameter("company_id") !== false)
			{
				$companyID = getRequestParameter("company_id");
				
			
			if(getRequestParameter("product_id") !== false)
			{
				$productID = getRequestParameter("product_id");
				$product = getProductByField($productID, "id");
				
				if($product["shop_id"] != $companyID)
				{
					$errors["company"] = translate("invalid_company");
				}
			}
			
			if(!$product)
			{
				$errors["product"] = translate("invalid_product");
			}
			
			if(!$client)
			{
				$loginPage = get_site_page_by_slug("login", $languageID);
				$errors["login"] = translate("you_must_login_to_send_message")."<br /><a class='btn btn-info' href='".site_url().$loginPage["url"].".html'>".$loginPage["name"]."</a>";
			}
			
			if(getRequestParameter("message") !== false && getRequestParameter("message") != "")
			{
				$message = getRequestParameter("message");
			}
			else
			{
				$errors["message"] = translate("invalid_message");
			}
			
			
			if(count($errors) > 0)
			{
				$response["errors"] = $errors;
			}
			else
			{
				$in["user_id"] = $client["id"];
				$in["product_id"] = $product["id"];
				$in["shop_id"] = $product["shop_id"];
				$in["message"] = $message;
				$in["date"] = time();
				$in["ip"] = $_SERVER['REMOTE_ADDR'];
				
				$messageID = $connection->insert("user_shop_contact_messages", $in);
				
				include("../helpers/Email.php");
				
				$content = translate("from")." : ".$client["name"]."\r\n <br />";
				$content .= nl2br($message);
				
				$email = new Email();
				$config['mailtype'] = 'html';
				
				$companyEmail = $product["company"]["email"];
				$companyName = $product["company"]["name"];
				
				$email->initialize ( $config );
				$email->from(get_setting("quote_email_address"), get_setting("site_name"));
				$email->to($companyEmail); 

				$email->subject(translate("contact_email")." - ".get_setting("site_name")."- #".$messageID);
				$email->message($content);	
				
				$email->send();
				
				$response["success"] = translate("company_contact_message_sent");
				
			}
		}
		echo json_encode($response);
	}

	if(getRequestParameter("what") == "get_qoute_form")
	{
		$products = array();
		$superCategory = $category = $subCategory = $bestCategory = false;
		
		$user = getLoginData();
		
		if(!$user)
		{
			$loginPage = get_site_page_by_slug("login", $_SESSION["language"]["id"]);
			
			echo translate("qoute_request_need_to_login");
			echo "<br /><a class='btn btn-primary btn-md' href='".site_url().$loginPage["url"].".html'>" . translate("log_in_now") . "</a>";
		}
		else
		{
			if(getRequestParameter("products") && getRequestParameter("products") != "")
			{
				$products = json_decode(getRequestParameter("products"), true);
			}
			if(count($products) > 0)
			{
					$products = getProductByField($products, "id");
			}
			else
			{
				if(getRequestParameter("super_category_id") && getRequestParameter("super_category_id") > 0)
				{
					$superCategory = $bestCategory = get_category_by_id(getRequestParameter("super_category_id"), $_SESSION["language"]["id"]);
				}
				
				if(getRequestParameter("category_id") && getRequestParameter("category_id") > 0)
				{
					$category = $bestCategory = get_category_by_id(getRequestParameter("category_id"), $_SESSION["language"]["id"]);
				}
				
				if(getRequestParameter("subcategory_id") && getRequestParameter("subcategory_id") > 0)
				{
					$subCategory = $bestCategory = get_category_by_id(getRequestParameter("subcategory_id"), $_SESSION["language"]["id"]);
				}
				
				$categories = get_category_hierarchy($_SESSION["language"]["id"]);
				
				
				$properties = get_category_properties($bestCategory["id"]);
			}
			
			include("../../html-includes/common/quote-form.php");
		}
	}
	
	if(getRequestParameter("what") == "get_subcategory_options" && getRequestParameter("category_id") > 0)
	{
		$categories = get_category_hierarchy($_SESSION["language"]["id"], getRequestParameter("category_id"));
		echo "<option value='0'>--------</option>";
		foreach($categories as $category)
		{
			echo "<option value='{$category["id"]}'>{$category["name"]}</option>";
		}
	}
	
	if(getRequestParameter("what") == "send_qoute_request")
	{
		$errors = array();
		$response = array();
		
		$user = getLoginData();
		if(!$user)
		{
			$loginPage = get_site_page_by_slug("login", $_SESSION["language"]["id"]);
			
			$errors["login"] = translate("qoute_request_need_to_login");
			$errors["login"] .= "<a href='".site_url().$loginPage["url"].".html'>" . translate("log_in_now") . "</a>";
			
			$response["errors"] = $errors;
			
			echo json_encode($response);
		}
		else
		{
			if(getRequestParameter("products"))
			{
				$categoryMail = false;
				
				$products = getProductByField(getRequestParameter("products"),"id");
				if(!$products)
				{
					$errors["products"] = translate("invalid_products");
				}
				else 
				{
					
				}
			}
			elseif(getRequestParameter("category_id") && getRequestParameter("category_id") > 0)
			{
				$categoryMail = true;
				
				$category = $bestCategory = get_category_by_id(getRequestParameter("category_id"), $_SESSION["language"]["id"]);
				
				if(getRequestParameter("subcategory_id") > 0)
				{
					$subCategory = $bestCategory = get_category_by_id(getRequestParameter("subcategory_id"), $_SESSION["language"]["id"]);
				}
			}
			
			if(!getRequestParameter("observations"))
			{
				$errors["observations"] = translate("invalid_message");
			}
			else
			{
				$observations = getRequestParameter("observations");
			}
			
			if(count($errors) == 0)
			{
				require_once("../helpers/Email.php");
				
				$emailContent = "
					<table cellpadding='5' cellspacing='0' border='0' style='width:600px'>
						<tr>
							<td colspan='6' style=''>
								<a href=".site_url()." title='' rel='nofollow' target='_blank'><img src='".scripts_url()."img/logo.png' alt='Mobilaro' /></a>
							</td>
						</tr>
					</table>
					<table cellpadding='10' cellspacing='0' border='0' style='width:600px'>
						<tr>
								<td>"
									.translate("qoute_request_email_text");
									
				$loginPage = get_site_page_by_slug("login", $_SESSION["language"]["id"]);
				$emailContent .= " <a href='".site_url().$loginPage["url"].".html' target='_blank' rel='nofollow'>" . translate("log_in_now") . "</a>";
				
				$emailContent .= "</td>
						</tr>";
				
				if($observations)
				{
					$emailContent .= "<tr><td><strong>".translate("observations").": </strong><br />".nl2br($observations)."</td></tr>";
				}
				$emailContent .= "</table>";
				
				if($categoryMail == true)
				{
					$companies = $connection->fetch_result("SELECT us.* FROM user_shops us
																LEFT JOIN products p ON p.shop_id = us.id
																LEFT JOIN products_categories pc ON pc.product_id = p.id
																WHERE pc.category_id = ? GROUP BY us.id", array($bestCategory["id"]));
				}
				else
				{
					foreach($products as $product)
					{
						$companies[$product["company"]["id"]] = $product["company"];
					}
				}
				foreach($companies as $company)
				{
					
					$in["user_id"] = $user["id"];
					$in["product_id"] = 0;
					$in["shop_id"] = $company["id"];
					$in["message"] = $emailContent;
					$in["date"] = time();
					$in["ip"] = $_SERVER['REMOTE_ADDR'];

					$messageID = $connection->insert("user_shop_contact_messages", $in);
					
					$email = new Email();
					$config['mailtype'] = 'html';
					
					$email->initialize ( $config );
					$email->from(get_setting("quote_email_address"), get_setting("site_name"));
					$email->to($company["email"]); 
	
					$email->subject(translate("qoute_email_title")." - ".get_setting("site_name")."- #".$messageID);
					$email->message($emailContent);	
					
					//$email->send();
				}
				$response["message"] = translate("qoute_request_sent");
			}
			else
			{
				$response["errors"] = $errors;
			}
			
			echo json_encode($response);
			
		}
	}
?>